import 'package:flutter/material.dart';

class PostSearchDelegate extends SearchDelegate<String> {
  final List<Map<String, String>> posts;
  final Function(String) onSearch;

  PostSearchDelegate(this.posts, {required this.onSearch});

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(onPressed: () => query = '', icon: const Icon(Icons.clear)),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () => close(context, ''),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    onSearch(query);
    close(context, query);
    return Container();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestions = posts
        .where((p) => p['title']!.toLowerCase().contains(query.toLowerCase()))
        .toList();

    return ListView.builder(
      itemCount: suggestions.length,
      itemBuilder: (_, index) {
        final item = suggestions[index];
        return ListTile(
          leading: CircleAvatar(backgroundImage: NetworkImage(item['avatar']!)),
          title: Text(item['title']!),
          onTap: () {
            query = item['title']!;
            showResults(context);
          },
        );
      },
    );
  }
}
